import base64
import pickle

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection

from carts import constants
from goods.models import SKU
from . import serializers


class CartView(APIView):
    def perform_authentication(self, request):
        """
        重写父类的用户验证方法，不在进入视图前就检查JWT
        """
        pass

    def post(self, request):
        """
        添加购物车
        :param request: 请求体
        :return: json
        """
        serializer = serializers.CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 尝试对请求的用户进行验证
        try:
            user = request.user
        except Exception:
            # 验证失败，用户未登录
            user = None

        # 判断客户是否登陆，登陆了也需要进行验证
        if user is not None and user.is_authenticated:
            # 链接redis数据库
            redis_cli = get_redis_connection('cart')

            p1 = redis_cli.pipeline()
            # 记录商品数量
            p1.hset('cart_%d' % user.id, sku_id, count)

            # 勾选
            if selected:
                p1.sadd('cart_selected_%d' % user.id, sku_id)
            p1.execute()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:
            # 用户未登录，在cookie中保存
            # {
            #     1001: { "count": 10, "selected": true},
            #     ...
            # }
            # 使用pickle序列化购物车数据，pickle操作的是bytes类型
            cart = request.COOKIES.get('cart')

            if cart:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

            # 判断购物车中是否有该商品
            sku = cart.get('sku_id')

            if sku:
                count = int(sku.get('count'))

            cart[sku_id] = {
                'count': count,
                'selected': selected
            }

            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            response = Response(serializer.data, status=status.HTTP_201_CREATED)
            # 设置cookie
            response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
            return response

    def get(self, request):
        """
        获取购物车
        :param request:
        :return: json
        """
        # 判断客户是否登陆
        try:
            user = request.user
        except:
            user = None
        if user is not None and user.is_authenticated:
            # 用户已登陆
            redis_cli = get_redis_connection('cart')
            redis_cart = redis_cli.hgetall('cart_%d' % user.id)
            redis_cart_selected = redis_cli.smembers('cart_selected_%d' % user.id)

            cart = {}
            # 从redis中取出的数据都是byte型
            for sku_id, count in redis_cart.items():
                cart[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in redis_cart_selected
                }
        else:
            # 用户未登录
            cart = request.COOKIES.get('cart')
            if cart:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

        # 遍历处理购物车数据
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]['count']
            sku.selected = cart[sku.id]['selected']

        serializer = serializers.CartListSerializer(skus, many=True)
        return Response(serializer.data)

    def put(self, request):

        serializer = serializers.CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 判断用户是否登陆
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 客户已经登陆
            redis_cli = get_redis_connection('cart')
            p1 = redis_cli.pipeline()
            p1.hset('cart_%d' % user.id, sku_id, count)
            if selected:
                p1.sadd('cart_selected_%d' % user.id, sku_id)
            else:
                p1.srem('cart_selected_%d' % user.id, sku_id)
            p1.execute()

            return Response(serializer.data)
        else:
            # 用户未登录，在cookie中保存
            # 使用pickle序列化购物车数据，pickle操作的是bytes类型
            cart = request.COOKIES.get('cart')

            if cart:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

            cart[sku_id] = {
                'count': count,
                'selected': selected
            }

            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            response = Response(serializer.data)
            # 设置购物车的cookie
            # 需要设置有效期，否则是临时cookie
            response.set_cookie('cart', cookie_cart, constants.CART_COOKIE_EXPIRES)

            return response

    def delete(self, request):

        serializer = serializers.CartDeleteSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')

        try:
            user = request.user
        except Exception:
            user = None

        if user and user.is_authenticated:
            redis_cli = get_redis_connection('cart')
            p1 = redis_cli.pipeline()
            # 删除redis数据库中存储的数据
            p1.hdel('cart_%d' % user.id, sku_id)
            p1.srem('cart_selected_%d' % user.id, sku_id)

            p1.execute()

            return Response(status=status.HTTP_204_NO_CONTENT)
        else:

            response = Response(status=status.HTTP_204_NO_CONTENT)
            cart = request.COOKIES.get('cart')

            if cart:
                cart = pickle.loads(base64.b64decode(cart.encode()))

                if sku_id in cart:
                    del cart[sku_id]

                    cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                    response.set_cookie('cart', cookie_cart, constants.CART_COOKIE_EXPIRES)

            return response
